package org.lim.domain.picture.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.lim.application.service.PictureCategoryApplicationService;
import org.lim.domain.picture.entity.PictureCategory;
import org.lim.domain.picture.service.PictureCategoryDomainService;
import org.lim.infrastructure.mapper.PictureCategoryMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 图片分类服务实现类
 */
@Service
public class PictureCategoryDomainServiceImpl extends ServiceImpl<PictureCategoryMapper, PictureCategory> implements PictureCategoryDomainService {

    @Override
    public List<PictureCategory> getActiveCategoryList() {
        QueryWrapper<PictureCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_active", 1)
                .orderByAsc("sort_order", "id");
        return this.list(queryWrapper);
    }

    @Override
    public PictureCategory getByCategoryName(String categoryName) {
        QueryWrapper<PictureCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_name", categoryName);
        return this.getOne(queryWrapper);
    }

    @Override
    public boolean batchAddCategories(List<String> categoryNames) {
        if (CollectionUtils.isEmpty(categoryNames)) {
            return true;
        }

        AtomicInteger sortOrder = new AtomicInteger(1);
        List<PictureCategory> categoryList = categoryNames.stream()
                .filter(categoryName -> categoryName != null && !categoryName.trim().isEmpty())
                .map(categoryName -> {
                    PictureCategory category = new PictureCategory();
                    category.setCategoryName(categoryName.trim());
                    category.setSortOrder(sortOrder.getAndIncrement());
                    category.setIsActive(1);
                    category.setCreateTime(new Date());
                    category.setUpdateTime(new Date());
                    return category;
                })
                .toList();

        return this.saveBatch(categoryList);
    }
}